#!/usr/bin/env bash
##############################
proot_container_main_menu() {
    case "$1" in
    restore | --restore) restore_tmoe_container ;;
    *) proot_container_menu ;;
    esac
}
################################
list_tmoe_containers() {
    ARCH_TYPE=${TRUE_ARCH_TYPE}
    rm ~/.config/tmoe-linux/across_architecture_container.txt 2>/dev/null
    case ${ARCH_TYPE} in
    mips* | riscv64)
        source "${TMOE_SHARE_DIR}"/container/qemu/qemu-user
        git_clone_debian_ports_distro
        ;;
    *) choose_which_gnu_linux_distro ;;
    esac
}
##############
across_architectures_container() {
    case ${TMOE_CHROOT} in
    true)
        case ${LINUX_DISTRO} in
        Android)
            # if [[ ! -e /proc/sys/fs/binfmt_misc ]]; then
            getprop ro.product.model 2>/dev/null
            # printf "%s %s\n" "部分Android系统无${BLUE}/proc/sys/fs/binfmt_misc${RESET}, 故本工具未对Android开放此功能。" "如需跨架构运行chroot容器，则请换用GNU/Linux系统，或自行加载${YELLOW}内核模块${RESET}。"
            printf "%s\n" "Sorry, you are using Android system, please ${GREEN}modprobe ${BLUE}binfmt_misc${RESET} kernel module manually."
            press_enter_to_return
            list_tmoe_containers
            # fi
            ;;
        esac
        ;;
    esac
    source "${TMOE_SHARE_DIR}"/container/qemu/qemu-user
    tmoe_qemu_user_manager
}
#############
proot_container_menu_multi_langs() {
    proot_container_menu_en() {
        SELECTED_GNU_LINUX=$("${TUI_BIN:-whiptail}" --title "${CONTAINER_TYPE} container" --menu "The current architecture is ${TRUE_ARCH_TYPE}." 0 50 0 \
            "1" "💠 ${TRUE_ARCH_TYPE} distros list" \
            "2" "📑 List installed" \
            "3" "⚔️ cross-architecture" \
            "4" "🔯 Restore ${CONTAINER_TYPE} container" \
            "5" "📕 Configuration & manual" \
            "0" "🌚 Back to the main menu" \
            3>&1 1>&2 2>&3)
    }
    proot_container_menu_cn() {
        SELECTED_GNU_LINUX=$("${TUI_BIN:-whiptail}" --title "${CONTAINER_TYPE}容器" --menu "The current architecture is ${TRUE_ARCH_TYPE}\n您是想要运行${TRUE_ARCH_TYPE}架构的容器,还是跨架构呢？\n除向下兼容外,跨架构运行的效率可能偏低" 0 50 0 \
            "1" "💠 ${TRUE_ARCH_TYPE}发行版列表" \
            "2" "📑 List installed 当前已安装容器列表" \
            "3" "⚔️ cross-architecture 跨CPU架构" \
            "4" "🔯 Restore 恢复/还原${CONTAINER_TYPE}容器" \
            "5" "📕 配置与手册" \
            "0" "🌚 Back to the main menu 返回主菜单" \
            3>&1 1>&2 2>&3)
    }
    #		"4" "switch 32/64bit proot" \
    #			"4" "切换32/64位版本proot" \
    # 4) switch_32_or_64_bit_proot ;;
    case ${TMOE_MENU_LANG} in
    zh_*UTF-8) proot_container_menu_cn ;;
    *) proot_container_menu_en ;;
    esac
    ##############################
    case "${SELECTED_GNU_LINUX}" in
    0 | "") tmoe_manager_main_menu ;;
    1) list_tmoe_containers ;;
    2) list_installed_tmoe_containers ;;
    3) across_architectures_container ;;
    4) restore_tmoe_container ;;
    5) configure_tmoe_container ;;
    esac
    ####################
    press_enter_to_return
    proot_container_menu_multi_langs
}
############
systemd_nspawn_is_false() {
    SYSTEMD_NSPAWN=false
    printf "%s\n" "SYSTEMD_NSPAWN=false" >${CONFIG_FOLDER}/chroot.conf
    grep --color=auto 'false' ${CONFIG_FOLDER}/chroot.conf
    chmod -v a+rw ${CONFIG_FOLDER}/chroot.conf
}
systemd_nspawn_is_true() {
    SYSTEMD_NSPAWN=true
    printf "%s\n" "SYSTEMD_NSPAWN=true" >${CONFIG_FOLDER}/chroot.conf
    grep --color=auto 'true' ${CONFIG_FOLDER}/chroot.conf
    chmod -v a+rw ${CONFIG_FOLDER}/chroot.conf
}
systemd_nspawn_is_true_or_false() {
    mkdir -pv ${CONFIG_FOLDER}
    # if [[ ${WINDOWS_DISTRO} = WSL || ${LINUX_DISTRO} = Android ]]; then
    # 	systemd_nspawn_is_false
    # else
    switch_chroot_default_mode
    # fi
}
switch_chroot_default_mode() {
    if ("${TUI_BIN:-whiptail}" --title "CHROOT MODE" --yes-button "systemd" --no-button "normal" --yesno "It is recommended to use the systemd mode.\nIf you want to use systemctl in the container,\nyou also need to enable the boot mode of nspawn.\nIf you cannot use the systemd mode,\nthen switch it back to the normal mode." 13 50); then
        systemd_nspawn_is_true
    else
        systemd_nspawn_is_false
    fi
    printf "%s\n" "This feature is only available for uncreated containers."
    printf "%s\n" "For the container that has been created, if you want to change the mode, please execute the following commands in the container."
    printf "%s\n" ""
    printf "${GREEN}%s${RESET}\n" "cd /usr/local/etc/tmoe-linux/container"
    printf "%s\n" "If you want to use the systemd mode, you can do so."
    printf "${GREEN}%s${RESET}\n" "ln -svf nspawn tmoe-linux-container ; sed -i -E 's@^(SYSTEMD_NSPAWN=).*@\1true@' chroot.conf"
    printf "%s\n" "If you want to use the normal mode, you can do so."
    printf "${GREEN}%s${RESET}\n" "ln -svf chroot tmoe-linux-container ; sed -i -E 's@^(SYSTEMD_NSPAWN=).*@\1false@' chroot.conf"
}
check_chroot_mode() {
    if [[ -s ${CONFIG_FOLDER}/chroot.conf ]]; then
        if ! grep -Eq '^[^#]*SYSTEMD_NSPAWN=' "${CONFIG_FOLDER}"/chroot.conf; then
            systemd_nspawn_is_true_or_false
        else
            SYSTEMD_NSPAWN=$(grep -E '^[^#]*SYSTEMD_NSPAWN=' "${CONFIG_FOLDER}"/chroot.conf | awk -F '=' '{print $2}')
        fi
    else
        systemd_nspawn_is_true_or_false
    fi

    case ${SYSTEMD_NSPAWN} in
    true)
        case ${TMOE_MENU_LANG} in
        zh_*UTF-8) TMOE_TIPS_04="当前为systemd模式。如需在容器内部使用systemctl,\n则还需要启用nspawn的boot模式" ;;
        *) TMOE_TIPS_04="Currently in systemd mode. If you want to use systemctl in the container,\nenable the boot mode of nspawn." ;;
        esac
        ;;
    false)
        case ${TMOE_MENU_LANG} in
        zh_*UTF-8) TMOE_TIPS_04="当前为normal模式" ;;
        *) TMOE_TIPS_04="Currently in normal mode." ;;
        esac
        ;;
    esac
}
chroot_container_menu_multi_langs() {
    chroot_container_menu_en() {
        SELECTED_GNU_LINUX=$("${TUI_BIN:-whiptail}" --title "${CONTAINER_TYPE} container" --menu "Chroot in normal mode is not suitable for production environment,\nit is recommended to use the systemd mode.\n${TMOE_TIPS_04}" 0 50 0 \
            "1" "💠 ${TRUE_ARCH_TYPE} distros list" \
            "2" "📑 List installed" \
            "3" "🥛 beta:switch chroot mode(systemd/normal)" \
            "4" "⚔️ cross-architecture" \
            "5" "🔯 Restore ${CONTAINER_TYPE} container" \
            "6" "📕 Configuration & manual" \
            "0" "🌚 Back to the main menu" \
            3>&1 1>&2 2>&3)
    }
    chroot_container_menu_cn() {
        SELECTED_GNU_LINUX=$("${TUI_BIN:-whiptail}" --title "${CONTAINER_TYPE}容器" --menu "由于普通模式的chroot在umount时可能会产生bug,\n故只适用于恢复环境,不适用于生产环境,建议您使用systemd模式。\n${TMOE_TIPS_04}" 0 50 0 \
            "1" "💠 ${TRUE_ARCH_TYPE}发行版列表" \
            "2" "📑 List installed 当前已安装容器列表" \
            "3" "🥛 beta公测:切换chroot默认模式(systemd/normal)" \
            "4" "⚔️ cross-architecture 跨CPU架构" \
            "5" "🔯 Restore 恢复/还原${CONTAINER_TYPE}容器" \
            "6" "📕 配置与手册" \
            "0" "🌚 Back to the main menu 返回主菜单" \
            3>&1 1>&2 2>&3)
    }
    check_chroot_mode
    if [[ ${SYSTEMD_NSPAWN} = true ]]; then
        systemd_nspawn_env
    fi
    case ${TMOE_MENU_LANG} in
    zh_*UTF-8) chroot_container_menu_cn ;;
    *) chroot_container_menu_en ;;
    esac
    ##############################
    case "${SELECTED_GNU_LINUX}" in
    0 | "") tmoe_manager_main_menu ;;
    1) list_tmoe_containers ;;
    2) list_installed_tmoe_containers ;;
    3) switch_chroot_default_mode ;;
    4) across_architectures_container ;;
    5) restore_tmoe_container ;;
    6) configure_tmoe_container ;;
    esac
    ####################
    press_enter_to_return
    chroot_container_menu_multi_langs
}
############
proot_container_menu() {
    source "${TMOE_SHARE_DIR}"/container/list
    check_proot_or_chroot
    SYSTEMD_NSPAWN=false
    RETURN_TO_WHERE='proot_container_menu'
    RETURN_TO_WHERE_02=${RETURN_TO_WHERE}
    case ${TMOE_CHROOT} in
    true) chroot_container_menu_multi_langs ;;
    *) proot_container_menu_multi_langs ;;
    esac
}
##################
systemd_nspawn_env() {
    if [ ! $(command -v systemd-nspawn) ]; then
        printf "${YELLOW}%s${RESET}\n" "Do you want to install systemd-container?${PURPLE}[Y/n]"
        printf "${GREEN}%s ${BLUE}%s${RESET}\n" "${TMOE_INSTALLATION_COMMAND}" "systemd-container"
        do_you_want_to_continue
        case ${LINUX_DISTRO} in
        Android)
            ${TMOE_INSTALLATION_COMMAND} systemd-container
            printf "%s\n" "${RED}Sorry${RESET}, this feature does not support ${BLUE}Android${RESET} system."
            printf "%s\n" "Please use the ${BLUE}normal mode${RESET}."
            ;;
        debian)
            apt update
            ${TMOE_INSTALLATION_COMMAND} systemd-container
            ;;
        *) ${TMOE_INSTALLATION_COMMAND} systemd-container ;;
        esac
    fi
    if [ ! $(command -v dbus-uuidgen) ]; then
        printf "${RED}%s${RESET}\n" "${RED}ERROR${RESET}！YOU DID NOT INSTALL DBUS."
        printf "${GREEN}%s ${BLUE}%s${RESET}\n" "${TMOE_INSTALLATION_COMMAND}" "dbus"
        systemd_nspawn_is_false
        press_enter_to_return
        chroot_container_menu_multi_langs
    fi
    #double check
    if [ ! $(command -v systemd-nspawn) ]; then
        printf "%s\n" "${RED}ERROR${RESET},you ${PURPLE}did not ${GREEN}install ${PURPLE}systemd-nspawn${RESET}."
        systemd_nspawn_is_false
        press_enter_to_return
        chroot_container_menu_multi_langs
    else
        systemctl list-units >/dev/null
        case ${?} in
        0) ;;
        *)
            printf "%s\n" "${RED}ERROR${RESET}, you can not use the systemd mode."
            printf "%s\n" "Please use the ${BLUE}normal mode${RESET}."
            systemd_nspawn_is_false
            press_enter_to_return
            chroot_container_menu_multi_langs
            ;;
        esac
    fi
    # list_installed_tmoe_containers
}
###############
restore_tmoe_container() {
    source "${TMOE_SHARE_DIR}"/compression/restore
    restore_gnu_linux_container
}
configure_tmoe_container() {
    source "${TMOE_SHARE_DIR}"/configuration/menu
    configure_tmoe_container
}
####################
proot_container_main_menu "$@"
